define([
    '../../framework/bean/common',
    '../../../modules/common/service',
    '../management/monitor/table/openAdchart',
    './table/adjustBudget',
    '../../framework/bean/admarket',
    '../../../modules/business/adMarketTarget/pauseDialog',
    './table/optlog'
], function(
    commonModel,
    $http,
    OpenAdchart,
    adjustBudget,
    admarketModel,
    PauseDialogView,
    OptlogView
) {
    function adOptimize() {
        var self = this;
        this.statusLabel = {
            ACTIVE: I18N.getText('management', 'active'),
            PAUSED: I18N.getText('management', 'paused'),
            DELETED: I18N.getText('management', 'deleted'),
            PENDING_REVIEW: I18N.getText('management', 'pendingReview'),
            DISAPPROVED: I18N.getText('management', 'disapproved'),
            PREAPPROVED: I18N.getText('management', 'preapproved'),
            PENDING_BILLING_INFO: I18N.getText('management', 'pendingBillingInfo'),
            CAMPAIGN_PAUSED: I18N.getText('management', 'campaignPaused'),
            ARCHIVED: I18N.getText('management', 'archived'),
            ADSET_PAUSED: I18N.getText('management', 'adsetPaused')
        };
        this.tableFields = {
            '3': 'todaySpent',
            '4': 'spent',
            '5': 'clicks',
            '6': 'ctr',
            '7': 'cpc',
            '8': 'purchase',
            '9': 'purchaseR',
            '10': 'cps',
            '11': 'salesAmount',
            '12': 'roi',
            '13': 'gaRoi',
            '14': 'budget',
            '15': 'bidAmount',
            '16': 'adCreatedUtcTime'
        };
        this.adMarket = {};
        this.init = function() {
            var _this = this;
            _this.$root = $(".admarket-container");
             var nmarketId = localStorage.getItem("adMarketId");
            if (!nmarketId || nmarketId == '') {
                return false;
            }
            _this.pauseDialogView = new PauseDialogView();
            _this.pauseDialogView.init($.proxy(_this.pauseAdCallback, _this));
            _this.optlogView = new OptlogView();
            _this.marketId = nmarketId;
            _this.render();
            _this.fillMarketTarget();
            _this.event();
        }
        this.render = function() {
            var _this = this;
            _this.initDate();
            _this.initTable();
            _this.initPauseadDialog();
        }
        this.initDate = function() {
            var _this = this;
            //渲染时间
            commonModel.timestamp(function(date) {
                var timezone = window.sessionStorage.timezoneValue;
                _this.nowDate = date.date;
                var nowDate = date.date;
                var daysOfWeek = [
                    I18N.getText('common', 'date_weekends'),
                    I18N.getText('common', 'date_monday'),
                    I18N.getText('common', 'date_tuesday'),
                    I18N.getText('common', 'date_wednesday'),
                    I18N.getText('common', 'date_thursday'),
                    I18N.getText('common', 'date_friday'),
                    I18N.getText('common', 'date_saturday')
                ];
                var monthNames = [
                    I18N.getText('common', 'date_january'),
                    I18N.getText('common', 'date_february'),
                    I18N.getText('common', 'date_march'),
                    I18N.getText('common', 'date_april'),
                    I18N.getText('common', 'date_may'),
                    I18N.getText('common', 'date_june'),
                    I18N.getText('common', 'date_july'),
                    I18N.getText('common', 'date_august'),
                    I18N.getText('common', 'date_september'),
                    I18N.getText('common', 'date_october'),
                    I18N.getText('common', 'date_november'),
                    I18N.getText('common', 'date_december')
                ];
                var config = {
                    maxDate: new Date(nowDate),
                    opens: 'right',
                    "alwaysShowCalendars": true,
                    locale: {
                        applyLabel: I18N.getText('management', 'dateApplyLabel'),
                        cancelLabel: I18N.getText('management', 'dateCancelLabel'),
                        fromLabel: I18N.getText('management', 'dateFromLabel'),
                        toLabel: window.sessionStorage.timezoneId + ':00',
                        customRangeLabel: I18N.getText('management', 'dateCustomRangeLabel'),
                        daysOfWeek: daysOfWeek,
                        monthNames: monthNames,
                        firstDay: 0,
                        format: 'YYYY-MM-DD'
                    },
                    endDate: moment(nowDate).subtract(1, 'day').utcOffset(timezone).format('YYYY-MM-DD'),
                    startDate: moment(nowDate).subtract(1, 'day').utcOffset(timezone).format('YYYY-MM-DD'),
                    drops: 'down',
                    ranges: {}
                }

                var today = moment(nowDate).utcOffset(timezone),
                    yesterday = moment(nowDate).utcOffset(timezone).subtract(1, 'days'),
                    forward_3_day = moment(nowDate).utcOffset(timezone).subtract(2, 'days'),
                    forward_7_day = moment(nowDate).utcOffset(timezone).subtract(6, 'days');
                //forward_30_day = moment(self.nowDate).utcOffset(timezone).subtract(29, 'days'),
                //forward_90_day = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(89, 'days'),
                //thisMonthBegin = moment(self.nowDate).utcOffset(self.timezoneValue).startOf('month'),
                //thisMonthEnd = moment(self.nowDate).utcOffset(self.timezoneValue).endOf('month'),
                //lastMonthBedin = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(1, 'month').startOf('month'),
                //lastMonthEnd = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(1, 'month').endOf('month');
                config.ranges[I18N.getText('management', 'dateRanges1')] = [today, today];
                config.ranges[I18N.getText('management', 'dateRanges2')] = [yesterday, today];
                config.ranges[I18N.getText('management', 'dateRanges3')] = [forward_3_day, today];
                config.ranges[I18N.getText('management', 'dateRanges7')] = [forward_7_day, today];

                $('.daterangepicker-sample3').daterangepicker(config, function(start, end, label) {});
            });
        }
        this.fillMarketTarget = function() {
            var _this = this;
            var params = {
                id: _this.marketId
            }
            admarketModel.findAdMarket(params, function(_result) {
                console.log(_result)
                if (_result == "" || kit.isEmptyObject(_result)) {
                    $(".no-admarket").removeClass("hide");
                    return;
                }
                $(".admarket-container").removeClass("hide");
                _this.adMarket = _result;
                $(".market-product").html(_result.productName);
                $(".market-feed").html(_result.feedWeName);
                $(".market-country").html(_result.targetCountryName);
                $(".market-budget").html("$" + Number(_result.dayBudget / 100).toFixed(2));
                $(".market-roi").html(_result.targetRoi);
                _this.renderPauseBtn(_result.opStatus);
            })
        }

        /**
         * { 右上角暂停按钮 }
         *
         * @param      {<type>}  opStatus  The operation status
         */
        this.renderPauseBtn = function(opStatus) {
            var $btn = $('.btn-pauseAd');
            var $status = $('.opt-status');
            var text = '';
            if (opStatus == 'creating') {
                text = I18N.getText('adMarketTarget','creating');
            } else if (opStatus == 'running') {
                text = I18N.getText('adMarketTarget','running');
                $btn.removeClass('hidden');
            } else if (opStatus == 'optimizing') {
                text = I18N.getText('adMarketTarget','optimizing');
            } else if (opStatus == 'fail') {
                text = I18N.getText('adMarketTarget','fail');
            } else if (opStatus == 'stop') {
                text = I18N.getText('adMarketTarget','stop');
            } else if (opStatus == 'stoping') {
                text = I18N.getText('adMarketTarget','stoping');
            } else {
                text = I18N.getText('adMarketTarget','exeption');
            }
            $status.text(text);
        }

        this.initPauseadDialog = function() {
            var _this = this;
            var pausedModal = $('#pausead-dialog');
            pausedModal.modal({
                backdrop: 'static',
                keyboard: false,
                show: false
            });

            $("select[name=pausead-reason-drop]", pausedModal).empty().select2({
                data: [{ text: I18N.getText("adOptimize", "continuousLowROI"), id: "CONTINUAL_ROI_LOW" },
                    { text: I18N.getText("adOptimize", "roiFluctuation"), id: "ROI_WAVE_HEAVILY" },
                    { text: I18N.getText("adOptimize", "CPSContinuousHigh"), id: "CONTINUAL_CPS_HIGH" },
                    { text: I18N.getText("adOptimize", "continuousLowCR"), id: "CONTINUAL_CR_LOW" },
                    { text: I18N.getText("adOptimize", "CPCContinuousHigh"), id: "CONTINUAL_CPC_HIGH" },
                    { text: I18N.getText("adOptimize", "CustomeRequirements"), id: "CUSTOM_REQUEST" }
                ],
                placeholder: I18N.getText("adOptimize", "PauseReasons"),
                multiple: true,
                allowClear: false,
                width: '100%'
            })

            pausedModal.off("show.bs.modal").on("show.bs.modal", function(e) {
                $("select[name=pausead-reason-drop]", pausedModal).val("").trigger("change");
                $(".pause-remainder", pausedModal).hide();
                self.restoreAdStatus = true;
            });

            pausedModal.off("hide.bs.modal").on("hide.bs.modal", function(e){
                if (self.restoreAdStatus){
                    var _switcher = self.$root.find('li[data-id="' + self.pausedDataId + '"]').find(".switcher");
                    _switcher.removeClass("disabled");
                    _switcher.find("label").addClass("active");
                }
            })

            $(".cancel-btn", pausedModal).off("click").on("click", function() {
                pausedModal.modal("hide");
            })

            $(".ok-btn", pausedModal).off("click").on("click", function() {
                var _attributions = $("select[name=pausead-reason-drop]", pausedModal).val();
                if (!_attributions || _attributions.length == 0) {
                    $(".pause-remainder", pausedModal).show();
                    return;
                }

                self.restoreAdStatus = false;
                var param = {
                    "optimizingType": "STOP_AD", // 取值范围 STOP_AD DOWN_BUDGET UP_BUDGET
                    "attributions": _attributions, // 修改原因（参考下面表格中的XX原因编号列）
                    "adId": _this.pausedAdId, // 修改目标广告ID
                    "adMarketTargetId": _this.adMarket.id,
                }

                $http.work("/admarket/optimizeAd", param, "POST").then(function(res) {
                    if (res.flag == "success" && res.data.jobId) {
                        _this.optimizeAdResult(res.data.jobId)
                    } else {
                        var _msg = res.msg;
                        if (!_msg || _msg == "") {
                            _msg = res.errorMsg;
                        }
                        if (!_msg || _msg == "") {
                            _msg = I18N.getText("adOptimize", "updateFailed");
                        }
                        kit.alert2(_msg)
                        self.getAllAds(self.param)
                    }
                }, function() {
                    kit.alert2(I18N.getText("adOptimize", "updateFailed"))
                    self.getAllAds(self.param)
                })
                pausedModal.modal("hide");
            });


        }
        this.optimizeAdResult = function(_jobId, okCallBack, failCallBack) {
            var _this = this;
            showAlert({
                content: '<h4>' + I18N.getText('management', 'synchronizing') + '</h4><div class="progressbar-default" name="line"></div>'
            });

            $('.progressbar-default').progressbar({
                css: 'progressbar-test-style',
                progress: 1 + '%',
                shape: 'default',
                width: 568,
                size: 5
            });

            //删除ok按钮
            $('#alert-holder button.btn.btn-default').remove();
            $('#alert-holder [data-dismiss="modal"]').off('click').on('click', function() {
                $('#alert-holder').modal('hide');
                $('#alert-holder').hide();
                clearTimeout(_this.setTimeoutId);
            });

            //连续请求jobId
            self.queryJob(_jobId, 1, okCallBack, failCallBack);
        }
        this.queryJob = function(_jobId, progress, successCallBack, failCallBack) {
            var _this = this;
            if (progress >= 99) {
                progress = 99;
            }
            $('.progressbar-default').progressbar('progress', progress + '%');

            var param = {
                jobId: _jobId
            }
            $http.work("/admarket/getJobStatus", param, "POST").then(function(res) {
                if (res.flag == "success") {
                    jobResult(_jobId, progress, res.data, successCallBack, failCallBack)
                } else {
                    var _msg = res.msg;
                    if (!_msg || _msg == "") {
                        _msg = res.errorMsg;
                    }
                    if (!_msg || _msg == "") {
                        _msg = I18N.getText("adOptimize", "updateFailed");
                    }
                    fail(failCallBack, _msg)
                }
            }, function() {
                fail(failCallBack, I18N.getText("adOptimize", "updateFailed"))
            })

            function success(_successCallBack) {
                if (_successCallBack) {
                    _successCallBack();
                }

                setTimeout(function() {
                    $('#alert-holder').modal('hide');
                    $('#alert-holder .close').trigger('click')
                }, 200);
                //提示同步成功
                kit.alert_success(I18N.getText('management', 'updateSuccess'));
                //状态恢复
                self.getAllAds(self.param);
            }

            function fail(_failCallBack, _msg) {
                if (_failCallBack) {
                    _failCallBack();
                }
                console.log(_msg)
                setTimeout(function() {
                    $('#alert-holder').modal('hide');
                    $('#alert-holder .close').trigger('click')
                }, 200);
                //提示错误信息
                showTip({
                    bind: $(".fmp-article"),
                    time: 1000,
                    type: "danger",
                    content: _msg,
                    icon: "<i class='font-icon font-icon-error'></i>",
                    close: true
                });

                //状态恢复
                self.getAllAds(_this.param);
            }

            function jobResult(_jobId, progress, _result, successCallBack, failCallBack) {
                var _status = _result.status;
                if (_status == "fail" || _status == "timeout" || _status == "success") {
                    if (_status == "success") {
                        console.log(_status)
                        success(successCallBack)
                    } else {
                        fail(failCallBack, _result.message || I18N.getText('management', 'updateFail'))
                    }
                } else {
                    //继续请求jobId
                    clearTimeout(self.setTimeoutId);
                    self.setTimeoutId = setTimeout(function() {
                        progress = (progress + parseInt(Math.random() * 20));
                        self.queryJob(_jobId, progress, successCallBack, failCallBack);
                    }, 2000);
                }
            }
        }
        this.initTable = function() {
            var _this = this;
            _this.treTable = $(".ndp-treable-wrapper", _this.$root).empty().treable({
                head: [{ label: '' }, //广告状态
                    { label: I18N.getText('management', 'name') }, //名称
                    { label: I18N.getText('management', 'status') }, //状态
                    { label: I18N.getText('management', 'todaySpent') }, //今日花费
                    { label: I18N.getText('management', 'spent') }, //总花费
                    { label: I18N.getText('management', 'clicks') }, //点击
                    { label: I18N.getText('management', 'ctr') }, //点击率
                    { label: I18N.getText('management', 'cpc') }, //成本
                    { label: I18N.getText('management', 'purchase') }, //转化率
                    { label: I18N.getText('management', 'purchaseR') }, //转化率
                    { label: I18N.getText('management', 'cps') }, //转化率
                    { label: I18N.getText('management', 'salesAmount') }, //转化率
                    { label: I18N.getText('management', 'roi') }, //转化率
                    { label: I18N.getText('adOptimize', 'gaRoi') }, //Ga投资回报率
                    { label: I18N.getText('management', 'budget') }, //预算
                    { label: I18N.getText('management', 'price') }, //出价
                    { label: I18N.getText('management', 'createTime') } //创建时间
                    // { label: I18N.getText('management', 'clicks') },//点击量
                ],
                body: [],
                tail: [{ text: 1000 }, { text: 1000 }, { text: 1000 }, { text: 1000 }, { text: 1000 }, { text: 1000 }, { text: 1000 }, { text: 1000 }, { text: 1000 }, { text: 1000 }],
                sort: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16], //base from 0
                todata: [
                    { name: I18N.getText('adOptimize', 'adjustBudget'), id: "adjust-price", class: 'adjust-price' },
                    { name: I18N.getText('management', 'chart'), id: "open-adchart", class: 'open-adchart' },
                ],
                tabs: [
                    { id: "0", name: 'Purchase & CPC', type: "line" },
                    { id: "0", name: "ROI & SalesAmount", type: "line" }
                ],
                scrollDOM: $(".fmp-article"),
                switcherDisable: true
            }).off("SORT_CLICK").on("SORT_CLICK", function(e) { //点击 排序按钮
                var _sort = e.originalEvent.data; // {col: "3", sort:"down" , val:"今日花费"}
                _this.param.sort = {
                    "field": _this.tableFields[_sort.col],
                    "type": _sort.sort == "down" ? -1 : 1
                }
                _this.param.cPage = 1;
                $(".ndp-treable-wrapper", _this.$root).find('.treable-header .sutable-col').removeClass("sort");
                var $col = $(".ndp-treable-wrapper", _this.$root).find('.treable-header .sutable-col[col="' + _sort.col + '"]');
                $col.addClass("sort");
                _this.getAllAds(_this.param);
            }).off("TOOLBAR_CLICK").on("TOOLBAR_CLICK", function(e) { // 点击最上面浮出的toolbar 或者，每一行的下拉菜单，[调整预算出价，编辑，看图表]
                console.log(e.originalEvent.data); //返回数据如下
                //{id: "chart", val: "看图表", name: "看图表", dataID: 11110}
                //id 点击的是哪个按钮，name：按钮的名字， dataID: 选中行(所在行)的数据id
                var d = e.originalEvent.data;
                var id = d.dataID;
                if (d.id == 'adjust-price') {
                    _this.adjustPrice(id);
                } else if (d.id == 'open-adchart') {
                    _this.openAdchart(id);
                }
            }).off("STATUS_CHANGE").on("STATUS_CHANGE", function(e) {
                $(".tip").remove();
                console.log(e.originalEvent.data); //返回数据如下
                var _d = e.originalEvent.data;
                _this.pausedAdId = _d.dataId.split("-")[1];
                _this.pausedDataId = _d.dataId;
                //弹出暂停原因框
                var pausedModal = $('#pausead-dialog');
                pausedModal.modal("show");
            }).off('RESIZE_DONE').on('RESIZE_DONE', $.proxy(self.resizeTable, this));

            _this.$root.find(".ndp-treable-wrapper .treable-footer").hide();
        }
        this.adjustPrice = function(_dataId) {
            var _this = this;
            console.log("调整预算出价");
            var ids = _dataId.split("-");
            var adSetId = ids[3];
            var adId = ids[1];
            new adjustBudget().init(adSetId, adId, _this.adMarket.id, _this.optimizeAdResult);
        }
        this.openAdchart = function(_dataId) {
            var _this = this;
            var $chartWrapper = $('.chart-wrapper[data-id="' + _dataId + '"]', _this.$root);
            var adId = _dataId.split('-')[1];
            setTimeout(function() {
                $('.chart-wrapper').find("div[role='tabpanel']").empty();
                $('.chart-wrapper').removeClass('open');
                $chartWrapper.addClass('open');
                $(".fmp-article").trigger("scroll");
                console.log("----传入趋势图的adId---" + _dataId);
                new OpenAdchart().init(adId, $chartWrapper, $(".ndp-treable-wrapper", _this.$root));
            }, 200);
        }
        this.event = function() {
            var _this = this;

            $(".query-btn", _this.$root).off("click").on("click", function() {
                var _dateRange = $('.daterangepicker-sample3').data('daterangepicker');
                _this.param = {
                    ecReport: true, // 固定参数
                    adMarketTargetId: _this.marketId,
                    statsTimeRange: {
                        since: _dateRange.startDate.format('YYYY-MM-DD'),
                        until: _dateRange.endDate.format('YYYY-MM-DD')
                    }, // 统计时间筛选条件（必须项，不需要转换时区，精确到天，格式请参考示例）
                    today: moment(_this.nowDate).utcOffset(window.sessionStorage.timezoneValue).format('YYYY-MM-DD'),
                    cPage: 1,
                    pSize: 10,
                    sort: {
                        field: "adCreatedUtcTime",
                        type: -1
                    }, // 排序参数，其中field代表排序字段，取值范围请参考统计数据字段一览，type代表排序类型（1代表升序，-1代表降序）（必须项）
                    returnStatsFields: [
                        "todaySpent",
                        "spent",
                        "clicks",
                        "ctr",
                        "cpc",
                        "purchase",
                        "purchaseR",
                        "cps",
                        "salesAmount",
                        "roi",
                        "gaRoi"
                    ]
                }
                $('span.sutable-col').removeClass("sort");
                $('span.sutable-col[col="16"]').addClass("sort");
                _this.getAllAds(_this.param);
            })

            $('.btn-pauseAd').off('click').on('click', function(e) {
                var id = kit.getUrlParam('id');
                _this.pauseDialogView.show(self.marketId);
            });
        }
        this.getAllAds = function(_param) {
            var _this = this;
            $http.work('/admarket/getAllAds', _param, 'POST').then(function(res) {
                var _newData;
                if (res.flag == "fail" || kit.isEmptyObject(res.data)) {
                    _newData = [];
                    _this.renderTable(_newData);
                    //渲染分页控件
                    _this.renderPage(_param.cPage, _param.pSize, 0);
                    //渲染表尾
                    _this.renderTableFooter(null);
                    var _msg = res.msg
                    if (res.errorMsg) {
                        _msg = res.errorMsg
                    }
                    if (_msg && _msg != "") {
                        kit.alert2(_msg)
                    }
                } else {
                    _newData = _this.parseAdsDatas(res.data.ads);
                    _this.renderTable(_newData);
                    //渲染分页控件
                    _this.renderPage(_param.cPage, _param.pSize, res.data.summary.adCount);
                    //渲染表尾
                    _this.renderTableFooter(res.data.summary);
                }

                _this.optlogView.init(_param);
            })
        }
        this.renderTableFooter = function(summary) {
            var _this = this;
            var $footer = _this.$root.find(".ndp-treable-wrapper .treable-footer");
            if (summary) {
                var footerHtml = '';
                var ad = I18N.getText('management', 'ads') + ' : ' + summary.adCount;
                footerHtml = footerHtml + '<span>' + ad + '</span> &nbsp;&nbsp;&nbsp;&nbsp;';
                if ((summary.spent + '').length > 0) { //花费
                    footerHtml = footerHtml + '<span>' + I18N.getText('adOptimize', 'spentWithFlag') + (' $ ' + kit.cent_to_dollar(summary.spent)) + '</span> &nbsp;&nbsp;&nbsp;&nbsp;';
                }
                if ((summary.cpc + '').length > 0) { //成本
                    footerHtml = footerHtml + '<span>' + I18N.getText('adOptimize', 'costWithFlag') + (' $ ' + kit.cent_to_dollar(summary.cpc)) + '</span> &nbsp;&nbsp;&nbsp;&nbsp;';
                }
                if ((summary.roi + '').length > 0) { //roi
                    footerHtml = footerHtml + '<span>' + I18N.getText('adOptimize', 'roiWithFlag') + (' ' + Number(summary.roi).toFixed(2)) + '</span> &nbsp;&nbsp;&nbsp;&nbsp;';
                }
                if ((summary.gaRoi + '').length > 0) { //gaRoi
                    footerHtml = footerHtml + '<span>' + I18N.getText('adOptimize', 'gaRoiWithFlag') + (' ' + Number(summary.gaRoi).toFixed(2)) + '</span> &nbsp;&nbsp;&nbsp;&nbsp;';
                }

                $footer.html('<li style="padding-top: 15px;padding-left: 20px;">' + footerHtml + '</li>');
                var isToShow = false;
                var showElement;
                $.each($footer, function(i, _$footer) {
                    var _d = $(_$footer).css("visibility");
                    if ("none" == $(_$footer).css("display")) {
                        isToShow = true;
                        showElement = $(_$footer)
                    }
                })
                if (isToShow) {
                    showElement.show();
                }
                self.resizeTable();
            } else {
                $footer.hide();
            }
        }

        this.resizeTable = function() {
            $('.treable-footer').width($('.ndp-treable-wrapper').width());
            $('.horiz-scroll').width($('.ndp-treable-wrapper').width());
        }

        this.renderPage = function(_currentPage, _perPage, _totalSize) {
            var _this = this;
            var _pageE = $("div.ndp-page-wrapper[name=drop-page]", _this.$root);
            _pageE.empty();
            if (_totalSize == 0){
                return;
            }


            _pageE.page({
                type: 3, //1 普通，2 带显示条数，3，简洁紧凑格式的菜单
                totalItems: _totalSize, //总共有n条数据
                perPage: _perPage, //每页默认显示10条
                currentPage: _currentPage,
                perPages: [10, 20, 50, 100]
            }).off("PAGE_CHANGE").on("PAGE_CHANGE", function(e) { //页数点击 事件
                console.log(e.originalEvent.data); //{currentPage: 第几页 int} currentPage: 1
                _this.param.cPage = e.originalEvent.data.currentPage;
                _this.getAllAds(_this.param);
            }).off("SHOW_ITEMS_CHANGE").on("SHOW_ITEMS_CHANGE", function(e) { //页数点击 事件
                console.log(e.originalEvent.data); //{currentPage: 第几页 int}  {currentPage: 1, perpage: 50}
                _this.param.cPage = e.originalEvent.data.currentPage;
                _this.param.pSize = e.originalEvent.data.perpage;
                _this.getAllAds(_this.param);

            });
        }
        this.parseAdsDatas = function(_ads) {
            var _this = this;
            var _newData = [];
            $.each(_ads, function(i, ad) {
                _newData.push({
                    id: ('ad-' + ad.adId + "-adSet-" + ad.adSetId),
                    label: [
                        { status: (ad.adConfiguredStatus == 'ACTIVE'), value: ad.adConfiguredStatus, disabled: !(ad.adConfiguredStatus == 'ACTIVE') }, //广告状态
                        { name: ad.adName + '', value: ad.adName }, //名称
                        { text: _this.statusLabel[ad.adStatus], value: ad.adStatus }, //状态
                        { text: _this._formatMoney(ad.todaySpent), value: ad.todaySpent }, //今日花费
                        { text: _this._formatMoney(ad.spent), value: ad.spent }, //总花费
                        { text: ad.clicks + '', value: ad.clicks }, //点击
                        { text: _this._formatPercent(ad.ctr), value: ad.ctr }, //点击率
                        { text: _this._formatMoney(ad.cpc), value: ad.cpc }, //CPC
                        { text: ad.purchase + '', value: ad.purchase }, //Purchase
                        { text: _this._formatPercent(ad.purchaseR), value: ad.purchaseR }, //PurchaseR
                        { text: _this._formatMoney(ad.cps), value: ad.cps }, //单次销售成本
                        { text: _this._formatMoney(ad.salesAmount), value: ad.salesAmount }, //SalesAmount
                        { text: ad.roi.toFixed(2) + '', value: ad.roi.toFixed(2) }, //ROI
                        { text: ad.gaRoi.toFixed(2) + '', value: ad.gaRoi.toFixed(2) },
                        { text: _this._formatMoney(ad.budget), value: ad.budget }, //预算
                        { text: _this._formatMoney(ad.bidAmount), value: ad.bidAmount }, //出价
                        { text: _this._formatLongTime(ad.adCreatedUtcTime), value: ad.adCreatedUtcTime } //创建时间
                    ]
                })
            })
            return _newData;
        }
        this.renderTable = function(_ads) {
            var _this = this;
            _this.treTable.update(_ads);
        }
        this._formatMoney = function(item) {
            return ((item || item == 0) ? (item == '-' ? '-' : '$ ' + kit.cent_to_dollar(item)) : '-') + '';
        }
        this._formatPercent = function(item) {
            return ((item || item == 0) ? (item == '-' ? '-' : kit.percentage(item)) : '-') + '';
        }
        this._formatLongTime = function(item) {
            return ((item || item == 0) ? (item == '-' ? '-' : kit.formatOffsetTime(item, window.sessionStorage.timezoneValue)) : '-') + '';
        }

        /**
         * { 更改暂停广告状态 }
         */
        this.pauseAdCallback = function() {
            $('.btn-pauseAd').addClass('hidden');
            $('.opt-status').text(I18N.getText('adMarketTarget','stoping'));
        }
    }

    return new adOptimize();
})
